package org.piggy.core.netty;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
import io.netty.util.AttributeKey;
import org.piggy.common.constants.OtherConst;
import org.piggy.core.netty.processor.NettyProcessor;
import org.piggy.core.netty.wrapper.HttpRequestWrapper;

public class NettyHttpServerHandler extends ChannelInboundHandlerAdapter {

    private final NettyProcessor nettyProcessor;

    public NettyHttpServerHandler(NettyProcessor nettyProcessor) {
        this.nettyProcessor = nettyProcessor;
    }

    @Override
    public void channelRead(ChannelHandlerContext channelHandlerContext, Object msg) {
        if(msg instanceof FullHttpRequest request){
            HttpRequestWrapper httpRequestWrapper = new HttpRequestWrapper();
            httpRequestWrapper.setChannelHandlerContext(channelHandlerContext);
            httpRequestWrapper.setRequest(request);
            nettyProcessor.process(httpRequestWrapper);
        }else if(msg instanceof WebSocketFrame request){
            Channel channel = (Channel) channelHandlerContext.channel().attr(AttributeKey.valueOf(OtherConst.FUTURE_2)).get();
            channel.writeAndFlush(request);
        }
    }
}
